Imports System.Configuration
Imports Microsoft.Win32

Public Class SQLAutoDocSVC
    Private moEventLog As EventLog

    Public Sub New()

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        Me.ServiceName = "SQLAutoDocSVC"
        Me.CanStop = True
        Me.CanPauseAndContinue = True
        Me.AutoLog = True

        moEventLog = New EventLog(logname:="Application", machinename:=".", source:="SQLAutoDocSVC")
    End Sub

    Protected Overrides Sub OnStart(ByVal args() As String)
        ' Add code here to start your service. This method should set things
        ' in motion so your service can do its work.
        Try
            moEventLog.WriteEntry("Service Starting.", System.Diagnostics.EventLogEntryType.Information)

            Dim oScanner As New SQLAutoDocLib.Scanner
            Dim sStartupInterval As String = oScanner.ServiceInterval

            If IsNumeric(sStartupInterval) Then
                timInterval.Interval = Val(sStartupInterval)
                timInterval.Enabled = True

                moEventLog.WriteEntry("Timer enabled for interval: " & sStartupInterval & ".", System.Diagnostics.EventLogEntryType.Information)
            Else
                timInterval.Enabled = False

                moEventLog.WriteEntry("RefreshInterval Configuration Setting missing or invalid.", System.Diagnostics.EventLogEntryType.Error)
            End If

        Catch oEX As Exception
            moEventLog.WriteEntry(oEX.Message, System.Diagnostics.EventLogEntryType.Error)
        End Try
    End Sub

    Protected Overrides Sub OnStop()
        ' Add code here to perform any tear-down necessary to stop your service.
        moEventLog.WriteEntry("Service Stopping.", System.Diagnostics.EventLogEntryType.Information)
        timInterval.Enabled = False
    End Sub

    Private Sub timInterval_Tick(ByVal sender As System.Object, ByVal e As System.Timers.ElapsedEventArgs) Handles timInterval.Elapsed
        Try
            GetMode()
        Catch oEX As Exception
            moEventLog.WriteEntry(oEX.Message, System.Diagnostics.EventLogEntryType.Error)

            Dim oLog As New ErrorLog.Log
            oLog.LogMessage(oEX)
        End Try
    End Sub

    Private Sub GetMode()
        Dim sMode As String = ConfigurationManager.AppSettings("Mode")

        If sMode = "web" Then
            ExecuteRemoteScan()

        ElseIf sMode = "svc" Then
            ExecuteLocalScan()
        Else
            moEventLog.WriteEntry("Invalid mode setting: " & sMode & " in configuration file.", System.Diagnostics.EventLogEntryType.Error)
        End If
    End Sub

    Private Sub ExecuteRemoteScan()
        Dim oKey As RegistryKey = Registry.LocalMachine
        Dim oSADKey As RegistryKey = oKey.OpenSubKey("SOFTWARE\jlion.com\SAD")

        Dim sVirtualDir As String = TrimQuotes(oSADKey.GetValue("VirtualDir"))
        Dim sURL As String = "http://" & My.Computer.Name & "/" & sVirtualDir & "/SQLAD.asmx"

        '---Get web service location
        Dim oSQLAD As New SQLAD
        oSQLAD.Url = sURL
        oSQLAD.Timeout = System.Threading.Timeout.Infinite

        '---Get timer interval
        Dim lInterval As Long = oSQLAD.ScanInterval
        If lInterval = 0 Then
            moEventLog.WriteEntry("Unable to retrieve timer interval or timer interval is 0.", System.Diagnostics.EventLogEntryType.Error)
            timInterval.Enabled = False
        Else
            timInterval.Interval = lInterval

            '---Execute remote scan
            oSQLAD.ScanDatabase()
        End If
    End Sub

    Private Sub ExecuteLocalScan()
        Dim oScanner As New SQLAutoDocLib.Scanner
        Dim sStartupInterval As String = oScanner.ServiceInterval
        If IsNumeric(sStartupInterval) _
            AndAlso Val(sStartupInterval) <> timInterval.Interval Then

            moEventLog.WriteEntry("Timer changed to interval: " & sStartupInterval & ".", System.Diagnostics.EventLogEntryType.Information)
            timInterval.Interval = Val(sStartupInterval)
        End If


        oScanner.Queue_ScanDatabase()
    End Sub

    Private Function TrimQuotes(ByVal sValue As String) As String
        Dim sResult As String = sValue

        If sResult.Length > 2 Then
            If sResult.Substring(0, 1) = Chr(34) Then
                sResult = sResult.Substring(1, sResult.Length - 1)
            End If

            If sResult.Substring(sResult.Length - 1, 1) = Chr(34) Then
                sResult = sResult.Substring(0, sResult.Length - 1)
            End If
        End If

        Return sResult
    End Function
End Class
